package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.Bookmark;
import com.conversationboard.model.Bookmarks;
import com.conversationboard.model.User;

@WebServlet(name = "BookmarksControllerServlet", urlPatterns = "/BookmarksControllerServlet")
public class BookmarksControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4729931974027051811L;


	private void deliverAsXML(HttpServletResponse response, Bookmarks bookmarks, User user) throws IOException {

		StringBuilder buffer = new StringBuilder();

		buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");

		buffer.append("<Bookmarks>");

		for (Bookmark bookmark : bookmarks) {

			if (bookmark.isUpdated()) {
				buffer.append("<Bookmark>");
				buffer.append("<BoardId>" + bookmark.getBoardId() + "</BoardId>");
				buffer.append("<ThreadId>" + bookmark.getThreadId() + "</ThreadId>");
				buffer.append("<MessageId>" + bookmark.getMessageId() + "</MessageId>");
				buffer.append("<Title><![CDATA[" + bookmark.getTitle() + "]]></Title>");
				buffer.append("</Bookmark>");
			}
		}

		buffer.append("</Bookmarks>");

		String xmlData = buffer.toString();
		String responseData = xmlData;

		response.getWriter().append(responseData);

	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			if (request.getUserPrincipal() == null) {
				return;
			}

			User user = User.get(request.getUserPrincipal().getName());
			Bookmarks bookmarks = user.getBookmarks();

			if (request.getParameter("xml") != null) {
				this.deliverAsXML(response, bookmarks, user);
			} else {
				request.setAttribute("bookmarks", bookmarks);

				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/bookmarks.jsp");
				dispatcher.forward(request, response);
			}

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
